package com.itheima.aop;

import com.itheima.anno.AutoFill;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;

import static com.itheima.constant.AutoFillConstant.SET_CREATE_TIME;
import static com.itheima.constant.AutoFillConstant.SET_UPDATE_TIME;

/**
 * @Author: 周训发
 * @CreateTime: 2025-10-22
 * @Description: 填充创建时间和更新时间
 * @Version: 1.0
 */

@Component
@Aspect
@Slf4j
public class AutoFillAspect {

    //定义公共切点表达式
//    @Pointcut("execution(* com.itheima.service.*.*(..))&& @annotation(com.itheima.anno.AutoFill)")
    public void autoFillPointCut(){}

//    @Before("autoFillPointCut()")
    public void AutoFillAOP(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("==========================AOP自动填充==========================");
        log.info("获得方法名：{}",joinPoint.getSignature().getName());
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        log.info("获得方法全类名：{}",signature);
        AutoFill autofill = signature.getMethod().getAnnotation(AutoFill.class);
        log.info("获得注解全类名，{}",autofill);
        OperationType operationType  = autofill.value();
        log.info("获得注解的值，{}",operationType);

        Object[] args = joinPoint.getArgs();
        log.info("获得参数列表，{}", Arrays.toString(args));
        if (args == null || args.length==0){
            return;
        }
        Object entity = args[0];
        log.info("第一个参数,{}",entity);

        if (operationType == OperationType.INSERT||operationType==OperationType.UPDATE){
            Method setCreateTime = entity.getClass().getDeclaredMethod(SET_CREATE_TIME, LocalDateTime.class);
            Method setUpdateTime = entity.getClass().getDeclaredMethod(SET_UPDATE_TIME, LocalDateTime.class);
            setCreateTime.invoke(entity,LocalDateTime.now());
            setUpdateTime.invoke(entity,LocalDateTime.now());
        }

    }


}
